/**   
* @Title: Util.java 
* @Package org.ay.ispringboot.common 
* @Description: TODO(用一句话描述该文件做什么) 
* @author AndyLi   
* @date Jan 29, 2018 6:15:49 PM 
* @version V1.0   
*/
package org.ay.ispringboot.common;

import java.security.MessageDigest;
import java.util.Collection;
import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Encoder;

/**
 * @author AndyLi
 *
 */
public class Util {
	private static Logger  logger = LoggerFactory.getLogger(Util.class);
	/**
	 * create hash key by md5
	 * @param sources
	 * @return
	 */
	public static String createHashKey(Object... sources){
		return encoderByMd5(createKeyStr(sources));
	}
	
	private static String createKeyStr(Object... sources) {
		StringBuilder sb = new StringBuilder();
		if(null != sources && sources.length > 0){
			
			for (Object s : sources) {
				if(null == s){
					logger.error("","create cache  hash key is null");
					continue;
				}else if(s.getClass().isArray()){
					for (Object obj : (Object[])s) {
						sb.append(createKeyStr(obj));
					}
				} else if(s instanceof Collection) {
					for (Object obj : (Collection<?>)s) {
						sb.append(createKeyStr(obj));	
					}
				} else if(s instanceof Date){
					Date date = (Date) s;
					sb.append(date.getTime()+"");
				}else{
					sb.append(s.toString());	
				}
				
				
			}
			
		}
		return sb.toString();
	}
	
	
	
	 /**using md5 to encryption string
     * @param str  the string will be encryption
     * @return  string after encryption
     * @throws NoSuchAlgorithmException  
     * @throws UnsupportedEncodingException  
     */
    public static String encoderByMd5(String str) {
    	try {
    		
            MessageDigest md5=MessageDigest.getInstance("MD5");
            BASE64Encoder base64en = new BASE64Encoder();
            
            String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
           return newstr;
            //return str;
		} catch (Exception e) {
			logger.error("",e);
		}
    	return "";
        
    }
    

}
